using System.Drawing;
using System.Windows.Forms;
using CloudShot.Entities;
using CloudShot.Logic;
using CloudShot.Properties;

namespace CloudShot.Editor.Tools.States
{
  public class CropSelectionState : IPointerToolState
  {
    private readonly IDrawingCanvas _canvas;
    private readonly ICursorService _cursorService;
    private readonly int _cropHandle;
    private Point _lastPoint;
    private readonly Cursor _cursor;
    private bool _spacePressed;

    public CropSelectionState(IDrawingCanvas canvas, ICursorService cursorService, int cropHandle, Point lastPoint)
    {
      _canvas = canvas;
      _cursorService = cursorService;
      _cropHandle = cropHandle;
      _lastPoint = lastPoint;

      _canvas.Crop.CurrentDragHandle = cropHandle;
      _cursor = _cursorService.Cursor;
    }

    public void OnMouseMove(Point point)
    {
      using (new AutomaticCanvasRefresher(_canvas, () => _canvas.Crop.GetBoundingBox()))
      {
        _canvas.Crop.IsShowSize = true;

        if (_cropHandle > 0 && !_spacePressed)
        {
          _canvas.Crop.MoveHandleTo(point, _cropHandle, _canvas.IsAnyModifierPressed(KeyModifiers.Shift));
          _cursorService.Cursor = _cursor;
        }
        else
        {
          int dx = point.X - _lastPoint.X;
          int dy = point.Y - _lastPoint.Y;

          _canvas.Crop.Move(dx, dy);
          _cursorService.Cursor = AppCursors.CropDragCursor;
        }

        _lastPoint.X = point.X;
        _lastPoint.Y = point.Y;
      }
    }

    public void OnKeyDown(KeyEventArgs keyEventArgs)
    {
      if ((keyEventArgs.KeyCode & Keys.Space) != 0)
      {
        _spacePressed = true;
        _cursorService.Cursor = AppCursors.CropDragCursor;
      }
    }

    public void OnKeyUp(KeyEventArgs keyEventArgs)
    {
      if ((keyEventArgs.KeyCode & Keys.Space) != 0)
      {
        _spacePressed = false;
        _cursorService.Cursor = _cursor;
      }
    }

    public void Enter()
    {
      if (_cropHandle != VertexType.None)
        _canvas.ShowHint(HintResources.CropTool_Sizing);
    }

    public void Release()
    {
      using (new AutomaticCanvasRefresher(_canvas, _canvas.Crop.GetBoundingBox))
      {
        _lastPoint = new Point(0, 0);
        _canvas.Crop.Normalize();
        _canvas.Crop.IsShowSize = false;
      }

      if (_cropHandle != VertexType.None)
        _canvas.HideHint();
    }
  }
}